package cz.data.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import cz.data.common.exception.DataException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class JsonCommon {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
        SecurityModuleUtil.registerJavaTimeModule(objectMapper);
        SecurityModuleUtil.registerSimpleModule(objectMapper);
    }

    public static String toJson(Object obj) {
        try {
            return objectMapper.writer().writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.warn("对象转json失败: {}", e.getMessage());
            throw new DataException(e.getMessage(), e);
        }
    }

    public static <T> T parseObject(String data, Class<T> clz) {
        return parseObject(data, clz, false);
    }

    public static <T> T parseObject(String data, Class<T> clz, boolean throwError) {
        try {
            return objectMapper.reader().readValue(data, clz);
        } catch (IOException e) {
            if (throwError)
                throw new DataException(String.format("Json转换错误: %s", e.getMessage()));
        }
        return null;
    }

    public static <T> T parseObject(String data, TypeReference<T> reference) {
        return parseObject(data, reference, false);
    }

    public static <T> T parseObject(String data, TypeReference<T> reference, boolean throwError) {
        try {
            return objectMapper.readerFor(reference).readValue(data);
        } catch (IOException e) {
            if (throwError)
                throw new DataException(String.format("Json转换错误: %s", e.getMessage()));
        }
        return null;
    }

    public static <T> T parseObject(byte[] data, Class<T> clz) {
        try {
            return objectMapper.reader().readValue(data, clz);
        } catch (IOException e) {
            throw new DataException(String.format("Json转换错误: %s", e.getMessage()));
        }
    }
}
